package cqrtplm.dto;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Data
public class RTDeptDTO {

    private String superior; //父id
    private String deptName;
    private String deptId;
    private List<RTDeptDTO> childDept;


    // 转换方法
    public static List<RTDeptDTO> convert(JSONArray allDept, String rootSuperior) {
        List<RTDeptDTO> all = new ArrayList<>();
        for (Object o : allDept) {

            RTDeptDTO dept = new RTDeptDTO();
            JSONObject jsonObject = (JSONObject) o;

            String deptId = jsonObject.getString("id");
            dept.setDeptId(deptId);
            dept.setDeptName(jsonObject.getString("name"));
            String superior = jsonObject.getString("superior");

            dept.setSuperior(superior);
            all.add(dept);
        }

        // 构建父子关系映射
        Map<String, List<RTDeptDTO>> childrenMap = new HashMap<>();
        // 构建父ID -> 子节点列表的映射
        for (RTDeptDTO dept : all) {
            childrenMap.computeIfAbsent(dept.getSuperior(), k -> new ArrayList<>()).add(dept);
        }
        List<RTDeptDTO> roots = new ArrayList<>(childrenMap.getOrDefault(rootSuperior, Collections.emptyList()));
        for (RTDeptDTO root : roots) {
            buildChildren(root, childrenMap);
        }

        return roots;
    }

    // 构建子树
    private static void buildChildren(RTDeptDTO parent, Map<String, List<RTDeptDTO>> childrenMap) {
        List<RTDeptDTO> children = childrenMap.getOrDefault(parent.getDeptId(), Collections.emptyList());
        parent.setChildDept(new ArrayList<>(children));
        for (RTDeptDTO child : parent.getChildDept()) {
            buildChildren(child, childrenMap);
        }
    }
}
